package com.zy.imagineCommunity.controller;


import com.alibaba.fastjson.JSONObject;
import com.zy.imagineCommunity.entity.*;
import com.zy.imagineCommunity.service.BlogService;
import com.zy.imagineCommunity.util.MarkdownUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.crypto.Data;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;


@Controller
public class BlogController {

    @Autowired
    BlogService blogService;

    @GetMapping("/blog")
    private String getBlog() {
        return "/write";
    }

    @ResponseBody
    @PostMapping("/sendBlog")
    public void sendBlog(String title, String content, String type, int userId, MultipartFile file) {
        //转html格式
        String markdownToHtml = MarkdownUtils.markdownToHtml(content);
        //最终存入数据库的图片地址
        String filepath = null;

        if (!file.isEmpty()) {
            try {
                // 时间戳
                String[] st = file.getOriginalFilename().split("\\.");
                int suffixIndex = st.length - 1;
                String exe = st[suffixIndex];
                Long timeStamp = System.currentTimeMillis();

                System.out.println("上传的文件名：" + file.getOriginalFilename());

                String fileName = timeStamp + "." + exe;
                String filePath = "e:\\test\\" + fileName;

                System.out.println("修改的文件名：" + filePath);
                System.out.println("/ImagineCommunity/test/" + fileName);

                filepath = "/ImagineCommunity/test/" + fileName;

                File saveFile = new File(filePath);
                if (!saveFile.getParentFile().exists())
                    saveFile.getParentFile().mkdirs();
                file.transferTo(saveFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            filepath = "/ImagineCommunity/c站.png";
        }

        int typeInt = 0;

        if ("Java".equals(type)) {
            typeInt = 10;
        } else if ("C++".equals(type)) {
            typeInt = 11;
        } else if ("Python".equals(type)) {
            typeInt = 12;
        } else if ("JavaScript".equals(type)) {
            typeInt = 13;
        } else if ("c语言".equals(type)) {
            typeInt = 14;
        } else if ("云计算".equals(type)) {
            typeInt = 15;
        }

        Date date = new Date();

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        //增加文章
        blogService.addBlog(new Blog(null, title, markdownToHtml, typeInt, filepath, userId, 0, simpleDateFormat.format(date)));

    }

    @GetMapping("/list/{type}/{pageNo}")
    private String getList(Model model, @PathVariable("type") int type, @PathVariable("pageNo") int pageNo) {

        Page<BlogText> page = blogService.queryBlogByTypeAndPageNoAndPageSize(type, pageNo, 10);

        if (type == 10) {
            model.addAttribute("blogListType", "Java");
        } else if (type == 11) {
            model.addAttribute("blogListType", "C++");
        } else if (type == 12) {
            model.addAttribute("blogListType", "Python");
        } else if (type == 13) {
            model.addAttribute("blogListType", "JavaScript");
        } else if (type == 14) {
            model.addAttribute("blogListType", "c语言");
        } else if (type == 15) {
            model.addAttribute("blogListType", "云计算");
        }

        model.addAttribute("type", type);

        model.addAttribute("pageNo", pageNo);

        model.addAttribute("page", page);

        return "/articleList";
    }

    @ResponseBody
    @GetMapping("/articleList")
    private JSONObject getArticleList(Model model, int type, int pageNo) {

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("type", type);

        jsonObject.put("pageNo", pageNo);

        return jsonObject;
    }

    @GetMapping("/lookArticleList/{type}/{pageNo}")
    private String articleList(Model model, @PathVariable("type") int type, @PathVariable("pageNo") int pageNo) {

        Page<BlogText> page = blogService.queryBlogByTypeAndPageNoAndPageSize(type, pageNo, 10);

        model.addAttribute("type", type);

        model.addAttribute("pageNo", pageNo);

        model.addAttribute("page", page);

        return "/articleList";
    }

    @GetMapping("/blogDetails")
    private String blogDetails(int id, Model model) {

        model.addAttribute("id", id);

        return "/blogDetails";
    }

    @ResponseBody
    @GetMapping("/getBlogDetails")
    private JSONObject getBlogDetails(int id) {
        JSONObject jsonObject = new JSONObject();

        BlogText blogText = blogService.queryBlogById(id);

        jsonObject.put("blogText", blogText);

        return jsonObject;
    }

    @GetMapping("/personalBlog")
    private String getPersonalBlog() {
        return "/PersonalBlogList";
    }

    @ResponseBody
    @GetMapping("/personalBlogList")
    public JSONObject personalBlogList(int userId, int pageNo) {

        //查询这一页的信息
        Page<BlogTextTwo> page = blogService.queryPersonalBlogByUserIdAndPageNoAndPageSize(userId, pageNo, 10);

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("page", page);

        return jsonObject;
    }

    @GetMapping("/deleteBlog")
    public String deleteBlog(int id) {
        blogService.deleteBlogById(id);
        return "forward:/personalBlog";
    }

    @GetMapping("/updatePersonalBlog")
    private String updatePersonalBlog(Model model, int id) {

        BlogText blogText = blogService.queryBlogById(id);

        //将字符转给普通字符串
        String content = MarkdownUtils.HtmlToText(blogText.getContent());

        BlogText blog = new BlogText(blogText.getId(), blogText.getTitle(), content, blogText.getType(), blogText.getFilePath(), blogText.getUserId(), blogText.getPraise(), blogText.getCreateTime(), blogText.getUserName(), blogText.getHeadImg());

        System.out.println(blog);

        model.addAttribute("blog", blog);

        return "/blogUpdate";
    }

    @ResponseBody
    @PostMapping("/updateBlog")
    public void updateBlog(int blogId, String title, String content, String type, int userId, MultipartFile file) {

        BlogText blogText = blogService.queryBlogById(blogId);
        //转html格式
        String markdownToHtml = MarkdownUtils.markdownToHtml(content);
        //最终存入数据库的图片地址
        String filepath = null;

        if (!file.isEmpty()) {
            try {
                // 时间戳
                String[] st = file.getOriginalFilename().split("\\.");
                int suffixIndex = st.length - 1;
                String exe = st[suffixIndex];
                Long timeStamp = System.currentTimeMillis();

                System.out.println("上传的文件名：" + file.getOriginalFilename());

                String fileName = timeStamp + "." + exe;
                String filePath = "e:\\test\\" + fileName;

                System.out.println("修改的文件名：" + filePath);
                System.out.println("/ImagineCommunity/test/" + fileName);

                filepath = "/ImagineCommunity/test/" + fileName;

                File saveFile = new File(filePath);
                if (!saveFile.getParentFile().exists())
                    saveFile.getParentFile().mkdirs();
                file.transferTo(saveFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            filepath = blogText.getFilePath();
        }

        int typeInt = 0;

        if ("Java".equals(type)) {
            typeInt = 10;
        } else if ("C++".equals(type)) {
            typeInt = 11;
        } else if ("Python".equals(type)) {
            typeInt = 12;
        } else if ("JavaScript".equals(type)) {
            typeInt = 13;
        } else if ("c语言".equals(type)) {
            typeInt = 14;
        } else if ("云计算".equals(type)) {
            typeInt = 15;
        }

        //根据id修改文章
        blogService.updateBlogById(new Blog(blogId, title, markdownToHtml, typeInt, filepath, blogText.getUserId(), 0, blogText.getCreateTime()));

    }

    /**
     * 提交搜索信息
     *
     * @param title
     * @param model
     * @return
     */
    @GetMapping("/blogSearchList")
    private String getBlogSearchList(String title, Model model) {
        System.out.println("你搜索的内容是：" + title);

        if ("Java".equals(title)) {

            return "forward:/list/10/1";

        } else if ("C++".equals(title)) {

            return "forward:/list/11/1";

        } else if ("Python".equals(title)) {

            return "forward:/list/12/1";

        } else if ("JavaScript".equals(title)) {

            return "forward:/list/13/1";

        } else if ("c语言".equals(title)) {

            return "forward:/list/14/1";

        } else if ("云计算".equals(title)) {

            return "forward:/list/15/1";

        }

        model.addAttribute("title", title);

        return "/blogSearchList";
    }

    /**
     * 搜索博客
     *
     * @param title
     * @param pageNo
     * @return
     */
    @ResponseBody
    @GetMapping("/searchBlog")
    public JSONObject searchBlog(String title, int pageNo) {
        System.out.println(title);
        //查询这一页的信息
        Page<BlogTextTwo> page = blogService.queryBlogByTitleAndPageNoAndPageSize(title, pageNo, 10);
        for (BlogTextTwo blogTextTwo : page.getItems()) {
            System.out.println(blogTextTwo);
        }
        JSONObject jsonObject = new JSONObject();

        jsonObject.put("page", page);

        return jsonObject;
    }

    /**
     * 点赞数
     *
     * @param blogId
     * @param userId
     * @return
     */
    @ResponseBody
    @GetMapping("/praiseBlog")
    public JSONObject praiseBlog(int blogId, int userId) {
        JSONObject jsonObject = new JSONObject();

        BlogText blogText = blogService.queryBlogById(blogId);

        //查找此用户是否对这条blog点赞
        Praise praise = blogService.queryPraiseByBlogIdAndUserId(blogId, userId);

        //如果没有点赞记录则增加记录并增加点赞数
        if (praise == null) {
            blogService.addPraise(new Praise(null, blogId, userId));
            blogService.updateBlogById(new Blog(blogId, blogText.getTitle(), blogText.getContent(), blogText.getType(), blogText.getFilePath(), blogText.getUserId(), blogText.getPraise() + 1, blogText.getCreateTime()));
            jsonObject.put("msg", "yes");
            return jsonObject;
        }
        //如果有点赞记录则删除记录并减少点赞数
        if (praise != null) {
            blogService.deletePraise(blogId, userId);
            blogService.updateBlogById(new Blog(blogId, blogText.getTitle(), blogText.getContent(), blogText.getType(), blogText.getFilePath(), blogText.getUserId(), blogText.getPraise() - 1, blogText.getCreateTime()));
            jsonObject.put("msg", "no");
            return jsonObject;
        }

        return jsonObject;
    }

    /**
     * 热门blog,6个
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/hotBlog")
    public JSONObject hotBlog() {
        //查询这一页的信息
        Page<BlogText> page = blogService.queryBlogByPraiseAndPageNoAndPageSize(1, 6);

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("page", page);

        return jsonObject;
    }

    @GetMapping("/toHotBlogList")
    private String toHotBlogList() {
        return "/HotBlogList";
    }

    /**
     * 热度排行
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/hotBlogList")
    public JSONObject hotBlogList(int pageNo) {
        //查询这一页的信息
        Page<BlogText> page = blogService.queryBlogByPraiseAndPageNoAndPageSize(pageNo, 10);

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("page", page);

        return jsonObject;
    }

    /**
     * 首页博客,每个板块10个
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/javaBlog/{type}")
    public JSONObject javaBlog(@PathVariable("type") int type) {
        JSONObject jsonObject = new JSONObject();

        if (type == 10) {

            Page<BlogTextTwo> page = blogService.queryBlogTextTwoByTypeAndBeginAndPageSize(type, 1, 10);

            jsonObject.put("javaPage", page);

            return jsonObject;
        } else if (type == 11) {

            Page<BlogTextTwo> page = blogService.queryBlogTextTwoByTypeAndBeginAndPageSize(type, 1, 10);

            jsonObject.put("cppPage", page);

            return jsonObject;
        } else if (type == 12) {

            Page<BlogTextTwo> page = blogService.queryBlogTextTwoByTypeAndBeginAndPageSize(type, 1, 10);

            jsonObject.put("pythonPage", page);

            return jsonObject;
        } else if (type == 13) {

            Page<BlogTextTwo> page = blogService.queryBlogTextTwoByTypeAndBeginAndPageSize(type, 1, 10);

            jsonObject.put("javaScriptPage", page);

            return jsonObject;
        } else if (type == 14) {

            Page<BlogTextTwo> page = blogService.queryBlogTextTwoByTypeAndBeginAndPageSize(type, 1, 10);

            jsonObject.put("cPage", page);

            return jsonObject;
        } else if (type == 15) {

            Page<BlogTextTwo> page = blogService.queryBlogTextTwoByTypeAndBeginAndPageSize(type, 1, 10);

            jsonObject.put("yPage", page);

            return jsonObject;
        }

        return jsonObject;
    }

    /**
     * 搜索个人博客
     *
     * @param userId
     * @param pageNo
     * @param searchValue
     * @return
     */
    @ResponseBody
    @GetMapping("/searchPersonalBlog")
    public JSONObject searchPersonalBlog(int userId, int pageNo, String searchValue) {

        //查询这一页的信息
        Page<BlogTextTwo> page = blogService.searchPersonalBlogByUserIdAndPageNoAndPageSizeAndSearchValue(userId, pageNo, 10, searchValue);

        JSONObject jsonObject = new JSONObject();

        jsonObject.put("page", page);

        return jsonObject;
    }

}
